<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" :inline="true" ref="queryFormRef" @keyup.enter.native="loadList">
				<el-row :gutter="10">
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="模型名称" prop="searchName">
							<el-input  v-model="state.pageParam.param.searchName" clearable/>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-button type="primary" class="ml7" @click="loadList">
							<el-icon>
								<ele-Search />
							</el-icon>
							查询
						</el-button>
						<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
							<el-icon>
								<ele-Refresh />
							</el-icon>
							重置
						</el-button>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card>
			<div class="btnStyle">
				<el-button  type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
				<el-button type="success"  icon="ele-Upload"  @click="()=>{ state.dialogVisible=true }">导入</el-button>
			</div>
			<el-table :data="state.dataList" stripe v-loading="state.listLoading" style="width: 100%;">
				<el-table-column prop="id" type="selection" width="50"> </el-table-column>
				<el-table-column prop="key" label="流程编码" width="200px"> </el-table-column>
				<el-table-column prop="name" label="模型名称"></el-table-column>
				<el-table-column v-if="state.istenant && userInfos.tenantId === '1'"
					prop="tenantId" header-align="center" align="center" label="租户" :formatter="formatTenant" />
				<el-table-column prop="version" width="150" label="当前版本" ></el-table-column>
				<el-table-column header-align="center" align="center" width="300" label="操作">
					<template  #default="scope">
						<el-button type="primary" link @click="updateHandle(scope.row.id)" >设计</el-button>
						<el-button type="primary" link @click="deleteHandle(scope.row.id)" >删除</el-button>
						<el-button type="primary" link @click="deployHandle(scope.row)" >发布</el-button>
						<el-button type="primary" link @click="exportXml(scope.row)">导出</el-button>
						<el-button type="primary" link @click="viewHisVersion(scope.row)">历史</el-button>
						<el-button type="primary" link @click="startProcess(scope.row)">发起流程</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.pageParam.page"
				background
				v-model:page-size="state.pageParam.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total" small>
			</el-pagination>
		</el-card>
		<el-dialog title="流程文件导入" v-model="state.dialogVisible" width="40%" class="customDialog" :close-on-click-modal="false">
			<el-upload class="upload-demo" ref="uploadRef" :file-list="state.fileList" :limit="10"
				multiple
				action="#"
				:before-upload="beforeupload"
				:on-exceed="handleExceed"
				:on-success="handleSuccess"
				:on-error="handleError"
				:http-request="uploadFile"
				:with-credentials='true'>
				<template #trigger>
					<el-button type="primary">选取文件</el-button>
				</template>
				<template #tip>
					<div class="el-upload__tip">
						只能上传.xml文件
					</div>
				</template>
			</el-upload>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">取消</el-button>
					<el-button type="primary" @click="submitUpload">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<deployVerHis  ref="deployVerHisRef" @refreshDataList="loadList"></deployVerHis>
		<dtartProcess ref="startProcessRef" @refreshDataList="loadList"></dtartProcess>
		<bpmnDesigner ref="bpmnDesignerRef" @refreshDataList="loadList"></bpmnDesigner>
	</div>
</template>
<script setup lang="ts" name="workflowModelList">
import { ref, reactive, onMounted, nextTick, defineAsyncComponent } from 'vue'
import { ElLoading, ElMessage, ElMessageBox, FormInstance, UploadInstance } from 'element-plus'
import { workflowApi } from '/@/api/sys/workflow-api'
import { systemApi } from '/@/api/sys/system-api'
import { useUserInfo } from '/@/stores/userInfo'
import { storeToRefs } from 'pinia'

const bpmnDesigner = defineAsyncComponent(() => import('./bpmn/index.vue'))
const deployVerHis = defineAsyncComponent(() => import('./deployVerHis.vue'))
const dtartProcess = defineAsyncComponent(() => import('./startProcessCommon.vue'))

const queryFormRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const bpmnDesignerRef = ref()
const deployVerHisRef = ref()
const startProcessRef = ref()
const { userInfos } = storeToRefs(useUserInfo())

const state = reactive({
	istenant: import.meta.env.VITE_IS_TENANT as Boolean,
	listLoading: false,
	dataList: [],
	total: 0,
	totalSelect: 0,
	pageParam: {
		page: 1,
		pageSize: 10,
		param: {
			searchName: '',
		}
	},
	dataListSelections: [],
	dialogVisible: false,
	fileList: [],
	dataTenantList: new Map<string, any>(),
})

const loadList = () => {
	state.listLoading = true
	workflowApi.getProcessDefinitionList(state.pageParam).then(data => {
		if (data && data.code === 0) {
			state.dataList = data.data.records
			state.total = data.data.totalRow
		} else {
			state.dataList = []
			state.total = 0
		}
	}).catch(() => {
	}).finally(() => {
		state.listLoading = false
	})
}
//重置
const reSetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    state.pageParam.page = 1
    loadList()
}
// 分页改变
const onHandleSizeChange = (val: number) => {
    state.pageParam.pageSize = val
    loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.pageParam.page = val
    loadList()
}
// 页面加载时
onMounted(() => {
	systemApi.getTenantSelect().then((data) => {
		if (data && data.code === 0) {
			data.data.forEach(function (item:any) {
				state.dataTenantList.set(item.key, item.value)
			})
		}

	})
	// 列表查询
	loadList()
})

//新增
const addOrUpdateHandle = () => {
	bpmnDesignerRef.value.openDialog();
}

// 设计
const updateHandle = (id: string) => {
	bpmnDesignerRef.value.openDialog(id, false)
}

//取消上传
const handleClose = () => {
	state.dialogVisible = false
	uploadRef.value!.clearFiles()
	state.fileList = []
	loadList()
}
const beforeupload = (file: any) => {
	var filename = file.name != null ? file.name : ''
	if (filename.indexOf('.xml') < 0) {
		ElMessage.error('只能导入xml文件')
		return false
	}
	return true
}
const handleExceed =  (files: any, fileList: any) => {
	ElMessage.error('一次只能导入10个文件！')
}
const handleSuccess = (response: any, file: any, fileList: any) => {
	// console.log(response.code)
	if (response.code === 0) {
		ElMessage.success('上传成功！')
	} else {
		ElMessage.error('上传失败！')
	}
}
const handleError = (err: any, file: any, fileList: any) => {
	ElMessage.error('上传失败！')
}
const uploadFile = (file: any) => {
// console.log(file.name)
}

//上传文件
const submitUpload = () => {
	let formData = new FormData()
	nextTick(() => {
		state.fileList.forEach((val, index) => {
			formData.append('file', val.raw)
		})
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		workflowApi.uploadModelFile(formData).then(data => {
			if (data && data.code === 0) {
				ElMessage.success('上传成功！')
				handleClose()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error('上传失败！')
		}).finally(() => {
			loading.close()
		})
	})
}

// 删除
const deleteHandle = (id: string) => {
	ElMessageBox.confirm('是否确定删除', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		})
		workflowApi.modelDeleteById(id).then((data) => {
			if (data && data.code === 0) {
				ElMessage.success('删除成功！')
				loadList()
			} else {
				ElMessage.error(data.message)
			}
		}).catch(() => {
			ElMessage.error('删除失败！')
		}).finally(() => {
			loading.close()
		})
	})
}
//导出
const exportXml = (row: any) => {
	workflowApi.exportXml(row.deploymentId)
}
// 发布流程
const deployHandle = (row: any) => {
	const loading = ElLoading.service({
		lock: true,
		text: '处理中',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	workflowApi.modelDeploy(row.id).then(data => {
		if (data && data.code === 0) {
			ElMessage.success('流程发布成功')
			loadList()
		} else {
			ElMessage.error(data.message)
		}
	})
	.catch(() => {
		ElMessage.error('流程发布失败')
	}).finally(() => {
		loading.close()
	})
}
const viewHisVersion = (row: any) => {
	deployVerHisRef.value.openDialog(row.id, row.key, row.deploymentId)
	/* workflowApi.getProcessDefinition(row.deploymentId).then((data) => {
		if (data && data.code === 0) {
		} else {
			ElMessage.error('获取流程历史版本失败')
		}
	}).catch(() => {
		ElMessage.error('获取流程历史版本失败')
	}) */
}
const startProcess = (row: any) => {
	ElMessage.warning('暂未支持从此处发起流程，请从业务功能发起流程')
}
const formatTenant = (row: any, column: any, cellValue: string, index: number) => {
	if(state.dataTenantList){
		if (cellValue) {
			return state.dataTenantList.get(cellValue)
		}
	}
}
</script>
